import {createSlice} from "@reduxjs/toolkit";
import {getWeibo, postWeibo} from "../../api/weibo";
import {useSelector} from "_react-redux@8.0.2@react-redux";

const weiboSlice = createSlice({
    name:"weibo",
    initialState:{
        contentList:[],// 微博列表
    },
    reducers:{
        upContentList(state,{payload}){
            state.contentList = payload;
        }
    }
})
export const {upContentList} = weiboSlice.actions;
export  const _getWeiboAsync = (pageNo=1,pageSize=30)=>{
    return async (dispatch)=>{
        const {contentList} = await getWeibo(pageNo,pageSize);
        dispatch(upContentList(contentList));
    }
}
export const postWeiboAsync = (contentRef)=>{
    return async (dispatch)=>{
        const content = contentRef.current.value.trim();
        if(content.length === 0){
            alert("请输入微博内容");
            return;
        }
        await postWeibo(content);
        contentRef.current.value = null;
        dispatch(_getWeiboAsync())
    }
}
export const useSelectorWeibo = ()=>{
    return  useSelector((state)=>{
        return state.weibo;
    });
}
export default weiboSlice.reducer;